<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/style/skin/default.css" media="all">
    <link rel="stylesheet" href="../css/style.css" media="all">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="../layui/layui.js"></script>
    <script src="../js/api.js"></script>
    <script src="index.js"></script>
</head>

<body>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>启文荣誉管理</legend>
    </fieldset>
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <button type="submit" class="layui-btn" id="demoSelect1" lay-filter="demo1">查询</button>
                </div>
            </div>

        </div>

    </form>


    <table class="layui-hide" id="test" lay-filter="testevent"></table>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="addItem">添加</button>
            <!-- <button class="layui-btn layui-btn-sm" lay-event="rangeDelete">批量删除</button> -->
        </div>
    </script>

    <!--    模板scripty-->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <!--上传图片弹框 -->
    <script id="uploadDialog" type="text/html">
        <div class="upload-image-list">
            <input type="file" id="file" style="display: none;" onchange=""> {{d.addHtml}}
        </div>

    </script>

    <!--添加图片按钮-->
    <script id="addDivHtml" type="text/html">
        <div class="addDiv" onclick="javascript:$('#file').trigger('click')">
            <img src="../image/add.png">
        </div>
    </script>


    <!--    弹出窗的模板-->
    <script type="text/html" id="argSchemaTemplate">
        <form class="layui-form" action="">
            <div class="layui-input-block" hidden>
                <input class="layui-input" type="text" name="id" value="{{d.id}}" autocomplete="off" placeholder="请输入id" />
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">荣誉名称</label>
                <div class="layui-input-block">
                    <input class="layui-input" type="text" lay-verify="required"  name="honorname"  value="{{d.honorname}}" autocomplete="off" placeholder="请输入名称" />
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">荣誉描述</label>
                <div class="layui-input-block">
                    <input class="layui-input" type="text" lay-verify="required"  name="honordes"  value="{{d.honordes}}" autocomplete="off" placeholder="请输入描述" />
                </div>
            </div>
            <div class="layui-upload">
                <label class="layui-form-label">图片添加</label>
                <button type="button" class="layui-btn" id="uploadId">上传图片</button>
                <div class="layui-upload-list">
                    <img class="layui-upload-img" id="uploadImgId" src="{{d.pic}}">
                    <p id="demoText"></p>
                </div>
            </div>

<!--            picUrl-->
            <div class="layui-form-item" hidden>
                <div class="layui-input-block" hidden>
                    <input class="layui-input" id="picUrl" type="text"  name="picUrl"  value="{{d.pic}}" autocomplete="off" />
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                 <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">提交</button>
            </div>
        </form>
    </script>
    <script type="text/html" id="PicurlTpl">
        <img class="layui-upload-img" id="uploadImgId21" src="{{d.pic}}">
   </script>
    <script type="text/javascript">
        var files = [];
        var postpicurl = '';
        layuiModules = ['table', 'form', 'laydate', 'admin', 'upload'];


        function mounted() {
            var form = layui.form
                , layer = layui.layer
                , laydate = layui.laydate;
            var table = layui.table;
            var $ = layui.$;
            var api = layui.api;
            var admin = layui.admin;
            var upload = layui.upload;

            postpicurl = api.advertDetail.upload;

            var where = {
                pageNo: 1,
                pageSize: 10,
                schoolId: 1
            };

            table.render({
                elem: '#test'
                , url: api.honormanager.all
                , cellMinWidth: 200 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , toolbar: '#toolbarDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                , page: false
                , contentType: "application/json"
                , parseData: function (res) {
                    // 调整符合表单的数据格式
                    // $(res.result).each(function () {
                    //     var oneDate = this;
                    //     for(var p in oneDate){
                    //         if (p === 'row') {
                    //             for (var attr in oneDate[p]) {
                    //                 oneDate[attr] = oneDate[p][attr];
                    //             }
                    //         }
                    //     }
                    // });
                    return {
                        "code": 0,
                        "msg": "",
                        "count": res.data.totalSize,
                        "data": res.data.result
                    }
                }
                , done: function (res, curr, count) {
                    loadPage(curr, count);
                }
                , cols: [[
                    { type: 'checkbox', fixed: 'left' }
                    , { field: 'id', width: 120, title: 'ID' }
                    , { field: 'pic', width: 120, title: '预览图片', templet: '#PicurlTpl' }
                    , { field: 'pic', width: 200, title: '图片链接' }
                    , { field: 'honorname', width: 200, title: '荣誉名称' }
                    , { field: 'honordes', width: 200, title: '荣誉描述' }
                    , { field: 'sortNumber', title: '排序', width: 200 }
                    , { fixed: 'right', width: 165, align: 'center', toolbar: '#barDemo' }
                ]]
                , where: where

            });

            form.render();

            // 后台接口分页参数不按Layui文档，自定义分页
            var repeat = [0, 0];
            function loadPage(curr, count) {
                if (repeat[0] == curr && repeat[1] == count) {
                    return false;
                }
                repeat[0] = curr;
                repeat[1] = count;
                layui.laypage.render({
                    elem: 'paging',
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    count: count,  //总数
                    limit: 10,   //每页显示的条数
                    skip: 1,
                    limits: [10, 20, 30, 40],
                    jump: function (obj) {
                        where.pageNo = obj.curr;
                        where.pageSize = obj.limit;
                        layui.table.reload('test', { where: where });
                        return false;
                    }
                });
            }
            function addItem(data) {
                admin.req({
                    url: api.honormanager.add,
                    data: data.field,
                    async: false,
                    success: function (res) {
                        layer.msg('新增成功');
                        layer.closeAll();
                        table.reload('test', { where: where });
                    }
                });
            }

            function updateItem(data) {
                admin.req({
                    url: api.honormanager.update,
                    data: data.field,
                    async: false,
                    success: function (res) {
                        layer.msg('修改成功');
                        layer.closeAll();
                        table.reload('test', { where: where });
                    }
                });
            }

            $('#demoSelect1').click(function () {
                layui.table.reload('test', { where: where });
            });

            //监听提交
            form.on('submit(demo1)', function (data) {
                if (data.field.id && data.field.id != 'undefined' && data.field.id != '') {
                    updateItem(data);
                } else {
                    addItem(data);
                }

                return false;
            });

            //监听头工具栏事件
            table.on('toolbar(testevent)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id)
                    , data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'addItem':
                        layer.msg('添加');
                        openlayer({ "honordes": '', "honorname": '', "id": '', "pic": '' });
                        // layui.laytpl($('#uploadDialog').html()).render({addHtml: $('#addDivHtml').html(),data:data}, function (html) {
                        //     console.log(html);
                        //     layer.open({
                        //         title: '上传',
                        //         type: 1,
                        //         content: html,
                        //         area: ['50%', '70%'],
                        //         btn:['确定','取消'],
                        //         yes:function (index, layero) {
                        //             //这里提交
                        //             var picUrls=[];
                        //             var objectPost={
                        //             }
                        //             files.forEach(value => {
                        //                 objectPost.picUrl=value.url;
                        //             });
                        //             picUrls.push(objectPost);
                        //             // addItem(picUrls);
                        //         },
                        //         btn2:function (index,layero) {
                        //         }
                        //     })
                        //
                        //     //多图片上传图片
                        //     $('#file').change(function () {
                        //         onFileUpload()
                        //     });
                        //
                        // });
                        break;
                    case 'rangeDelete':
                        //批量删除
                        break;
                    case 'rangeExport':

                        break;
                };
            });

            //监听行工具事件
            table.on('tool(testevent)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    , layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'detail') {
                    layer.msg('查看操作');
                    //图片管理
                } else if (layEvent === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close(index);
                        //向服务端发送删除指令
                        admin.req({
                            url: `${api.honormanager.delete}?id=${obj.data.id}`,
                            contentType: 'application/x-www-form-urlencoded',
                            async: false,
                            success: function (res) {
                                layer.msg('删除成功');
                            }
                        });
                    });
                } else if (layEvent === 'edit') {
                    layer.msg('编辑操作');
                    openlayer(data)

                }
            });
            /**
             * 类Vue路由设计
             */
            function initRouter() {
                var url = '#/advertmanager.html';
                var router;
                if (url.indexOf("#/") > -1) {
                    router = url.substring(url.indexOf('#/') + 2);
                    if (router === '') {
                        router = 'index.html';
                    }
                    $('#iframeParent').attr('src', 'html/' + router);
                } else {
                    $('#iframeParent').attr('src', 'html/index.html');
                    history.replaceState(null, null, '#/');
                }
                //地址栏修改不刷新的解决方案
                // $('a').click(function () {
                //     if ($(this).attr('href')) {
                //         window.location.href = $(this).attr('href');
                //         window.location.reload();
                //     }
                // });
            }

            function openlayer(data) {
                var templet = $('#argSchemaTemplate').html();

                layui.laytpl(templet).render(data, function (html) {
                    //layer 弹出窗
                    //在这里面输入任何合法的js语句
                    layer.open({
                        type: 1 //Page层类型
                        , area: ['500px', '500px']
                        , title: '添加'
                        , shade: 0.6 //遮罩透明度
                        , maxmin: false //允许全屏最小化
                        , anim: -1 //0-6的动画形式，-1不开启
                        , content: html,
                        success: function (layero, index) {

                            //普通图片上传
                            var uploadInst = upload.render({
                                elem: '#uploadId'
                                , url: api.advertDetail.upload //改成您自己的上传接口
                                , before: function (obj) {
                                    //预读本地文件示例，不支持ie8
                                    obj.preview(function (index, file, result) {
                                        $('#uploadImgId').attr('src', result); //图片链接（base64）
                                    });
                                }
                                , done: function (res) {
                                    //如果上传失败
                                    if (res.code > 0) {
                                        return layer.msg('上传失败');
                                    }
                                    //上传成功
                                    $('#picUrl').val(res.data);
                                    data.pic = res.data;
                                    // updateItem(data)
                                }
                                , error: function () {
                                    //演示失败状态，并实现重传
                                    var demoText = $('#demoText');
                                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                                    demoText.find('.demo-reload').on('click', function () {
                                        uploadInst.upload();
                                    });
                                }
                            });
                        }
                    });
                });
            }

            /**
             * 上传图片
             */
            function uploadFn(picdata) {
                var formData = new FormData();
                formData.append('file', picdata);
                $.ajax({
                    url: postpicurl,
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data.code == 0) {
                            // $("#preview_photo").attr("src", data.filepath+data.filename);
                            // $("#productImg").val(data.filename);
                            picdata.url = data.data;
                            console.log(JSON.stringify(files));
                            var objData = {};
                            objData.picUrl = data.data;
                            addItem(objData);
                        } else {
                            alert(data.msg);
                        }
                        alert("上传成功")
                    },
                    error: function (data) {
                        alert("上传失败")
                    }
                });
            }

            /**
             * 图片选择回调
             */
            function onFileUpload() {
                console.log($('#file')[0].files[0]);
                files.push($('#file')[0].files[0]);
                uploadFn($('#file')[0].files[0]);
                var reads = new FileReader();
                reads.readAsDataURL($('#file')[0].files[0]);
                reads.onload = function () {
                    //this.result
                    $('.upload-image-list').html(
                        $('.upload-image-list').html().replace($('#addDivHtml').html(), '')
                        + `<div class="item">
                    <img class="image" src="${this.result}"/>
                    <img src="../image/delete.png" class="delete" onclick="">
                </div>`
                        + $('#addDivHtml').html());

                    $('.delete').click(function () {
                        deleteImg();
                    });

                    //多图片上传图片
                    $('#file').change(function () {
                        onFileUpload()
                    });
                };
            }

            /**
             * 删除图片
             * @param index
             */
            function deleteImg(index) {
                index = 0;
                console.log(files);
                files.splice(index, 1);
                $(`.upload-image-list .item`)[index].className = "delItem";
            }

        };

    </script>
</body>

</html>